﻿// See https://aka.ms/new-console-template for more information

using System.Configuration;
using Sora;
using Sora.Entities;
using Sora.Interfaces;
using Sora.Net.Config;
using Sora.Util;
using Sora.EventArgs.SoraEvent;
using YukariToolBox.LightLog;

Log.LogConfiguration
    .EnableConsoleOutput()
    .SetLogLevel(
#if Debug
        LogLevel.Debug
#else
        LogLevel.Info
#endif
        );

ISoraService service = SoraServiceFactory.CreateService(GetClientConfig());

// ISoraService service = SoraServiceFactory.CreateService(new ServerConfig()
// {
//     AccessToken = "123456",
//     Port = 9000
// });

// service.Event.OnGroupMessage += async (sender, eventArgs) =>
// {
//     if (eventArgs.SourceGroup.Id == )
//     {
//         await eventArgs.SourceGroup.SendGroupMessage(eventArgs.Message.MessageBody);
//     }
// };

await service.StartService()
    .RunCatch(e => Log.Error("Sora Service", Log.ErrorLogBuilder(e)));
await Task.Delay(-1);

ClientConfig GetClientConfig()
{
    try
    {
        var config = ConfigurationManager.OpenExeConfiguration(Environment.ProcessPath);
        var settings = config.AppSettings.Settings;

        string? ReadSetting(string key)
        {
            if (settings[key] is null)
                return null;
            return settings[key].Value;
        }

        return new ClientConfig
        {
            AccessToken = ReadSetting("AccessToken") ?? string.Empty,
            Port = ushort.Parse(ReadSetting("Port") ?? "6700"),
            Host = ReadSetting("Host") ?? "127.0.0.1",
        };
    }
    catch (ConfigurationErrorsException)
    {
        Console.WriteLine("Error reading app settings. Use default settings");
        return new();
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        throw;
    }
}